package com.example.bgxqwebsocket.dao;

import com.example.bgxqapi.domain.dao.Message;
import com.example.bgxqapi.domain.dto.UnreadUserMessage;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * @author lizijian
 */
@Mapper
public interface MessageDao {

  /**
   * 插入消息
   *
   * @param message 消息对象
   * @return
   */
  @Insert("INSERT INTO message (content,from_user_id,to_user_id,type,time) VALUES (#{content},#{fromUserId},#{toUserId},#{type},#{time})")
  @Options(keyProperty = "id", keyColumn = "id", useGeneratedKeys = true)
  void addMessage(Message message);

  /**
   * 撤回消息
   * @param id
   */
  @Delete("DELETE FROM message WHERE id = #{id}")
  void deleteMessage(int id);

  /**
   * 插入未读消息
   * @param messageId
   */
  @Insert("INSERT INTO unread_message (message_id) VALUES (#{messageId})")
  void addUnreadMessage(int messageId);

  /**
   * 查询指定id用户发送的未读消息
   */
  @Select("SELECT message.id,content,type,message.create_time,message.time FROM unread_message,message WHERE message.from_user_id =#{objectId} AND message.to_user_id =#{myId} AND unread_message.message_id=message.id  ")
  List<UnreadUserMessage> getUnreadMessageByUserId(@Param("objectId") int objectId,@Param("myId") int myId);

  /**
   * 删除指定messageId的未读消息
   * @param messageIds messageId数组
   */
  @Delete("<script>DELETE FROM unread_message WHERE message_id IN (<foreach collection= 'list' item='item' separator=','>#{item}</foreach>)</script>")
  void deleteUnreadMessageByUserId(@Param("list") int [] messageIds);

  /**
   * 查询指定id消息
   * @param id
   * @return
   */
  @Select("SELECT * FROM message WHERE id= #{id}")
  Message getMessageById(int id);


  /**
   * 将未读消息标记撤回
   * @param messageId
   */
  @Update("UPDATE unread_message SET is_withdraw =1 WHERE message_id = #{messageId}")
  void withdraw(int messageId);

}
